/**
 * 
 */
package us.gaaoc.framework.dao;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

import org.apache.log4j.Logger;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Example;

public abstract class GenericHibernateDAO<T, ID extends Serializable, DAOImpl extends GenericDAO<T, ID>> implements
		GenericDAO<T, ID> {

	private Class<T> persistentClass;
	private Session session;
	Logger LOG = Logger.getLogger(GenericHibernateDAO.class);

	@SuppressWarnings("unchecked")
	protected GenericHibernateDAO() {
		this.persistentClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
	}

	@SuppressWarnings("unchecked")
	public DAOImpl setSession(Session s) {
		this.session = s;
		return (DAOImpl) this;
	}

	protected Session getSession() {
		if (session == null){
			LOG.info("Session has not been set on DAO before usage");
			throw new IllegalStateException("Session has not been set on DAO before usage");
		}
		//LOG.info("there is a session");			
		return session;
	}

	public Class<T> getPersistentClass() {
		return persistentClass;
	}
	
	@SuppressWarnings("unchecked")
	public T findById(ID id) {
		T entity;
		entity = (T) getSession().load(getPersistentClass(), id);
		return entity;
	}

	public List<T> findAll() {
		return findByCriteria();
	}

	@SuppressWarnings("unchecked")
	public List<T> findByExample(T exampleInstance, String[] excludeProperty) {
		Criteria crit = getSession().createCriteria(getPersistentClass());
		Example example = Example.create(exampleInstance);
		for (String exclude : excludeProperty) {
			example.excludeProperty(exclude);
		}
		crit.add(example);
		return crit.list();
	}

	public T makePersistent(T entity) {
		getSession().save(entity);
		LOG.info("4. Inside the makePersistent of the GenericHibernateDAO");
		return entity;
	}

	public void makeTransient(T entity) {
		LOG.info("Inside the maksTransient...");
		getSession().delete(entity);
	}

	/**
	 * Use this inside subclasses as a convenience method.
	 */
	@SuppressWarnings("unchecked")
	protected List<T> findByCriteria(Criterion... criterion) {
		Criteria crit = getSession().createCriteria(getPersistentClass());
		for (Criterion c : criterion) {
			crit.add(c);
		}
		return crit.list();
	}

}